<?php
/**
 * 点大商城（www.diandashop.com） - 微信公众号小程序商城系统!
 * Copyright © 2020 山东点大网络科技有限公司 保留所有权利
 * =========================================================
 * 版本：V2
 * 授权主体：shop.guanjunbang.cn
 * 授权域名：shop.guanjunbang.cn
 * 授权码：vdcajlVLIVAgVdkfJvgY
 * ----------------------------------------------
 * 您只能在商业授权范围内使用，不可二次转售、分发、分享、传播
 * 任何企业和个人不得对代码以任何目的任何形式的再发布
 * =========================================================
 */

// +----------------------------------------------------------------------
// | 佣金管理
// +----------------------------------------------------------------------
namespace app\controller;
use think\facade\View;
use think\facade\Db;

class Commission extends Common
{
	public function initialize(){
		parent::initialize();
		if(bid > 0) showmsg('无操作权限');
	}
	//佣金记录
    public function record(){
		if(request()->isAjax()){
			$page = input('param.page');
			$limit = input('param.limit');
			if(input('param.field') && input('param.order')){
				$order = 'member_commission_record.'.input('param.field').' '.input('param.order');
			}else{
				$order = 'member_commission_record.id desc';
			}
			$where = [];
			$where[] = ['member_commission_record.aid','=',aid];
			$where[] = ['member_commission_record.status','in',[0,1]];
			
			if(input('param.nickname')) $where[] = ['member.nickname','like','%'.trim(input('param.nickname')).'%'];
			if(input('param.mid')) $where[] = ['member_commission_record.mid','=',trim(input('param.mid'))];
			if(input('?param.status') && input('param.status')!=='') $where[] = ['member_commission_record.status','=',input('param.status')];
			$count = 0 + Db::name('member_commission_record')->alias('member_commission_record')->field('member.nickname,member.headimg,member_commission_record.*')->join('member member','member.id=member_commission_record.mid')->where($where)->count();
			$data = Db::name('member_commission_record')->alias('member_commission_record')->field('member.nickname,member.headimg,member_commission_record.*')->join('member member','member.id=member_commission_record.mid')->where($where)->page($page,$limit)->order($order)->select()->toArray();
			
			foreach($data as $k=>$v){
				if($v['type'] == 'levelup'){
					$data[$k]['orderstatus'] = 1;
				}else{
					$data[$k]['orderstatus'] = Db::name($v['type'].'_order')->where('id',$v['orderid'])->value('status');
				}
				if($v['frommid']){
					$frommember = Db::name('member')->where('id',$v['frommid'])->find();
					if($frommember){
						$data[$k]['fromheadimg'] = $frommember['headimg'];
						$data[$k]['fromnickname'] = $frommember['nickname'];
					}
				}
			}
			return json(['code'=>0,'msg'=>'查询成功','count'=>$count,'data'=>$data]);
		}
		return View::fetch();
    }
	//佣金记录导出
	public function recordexcel(){
		if(input('param.field') && input('param.order')){
			$order = 'member_commission_record.'.input('param.field').' '.input('param.order');
		}else{
			$order = 'member_commission_record.id desc';
		}
		$where = [];
		$where[] = ['member_commission_record.aid','=',aid];
		
		if(input('param.nickname')) $where[] = ['member.nickname','like','%'.trim(input('param.nickname')).'%'];
		if(input('param.mid')) $where[] = ['member_commission_record.mid','=',trim(input('param.mid'))];
		if(input('?param.status') && input('param.status')!=='') $where[] = ['member_commission_record.status','=',input('param.status')];
		$list = Db::name('member_commission_record')->alias('member_commission_record')->field('member.nickname,member.headimg,member_commission_record.*')->join('member member','member.id=member_commission_record.mid')->where($where)->order($order)->select()->toArray();
		$title = array();
		$title[] = t('会员').'信息';
		$title[] = '佣金';
		$title[] = '积分';
		$title[] = '状态';
		$title[] = '产生时间';
		$title[] = '发放时间';
		$title[] = '备注';
		$data = array();
		foreach($list as $v){
			$tdata = array();
			$tdata[] = $v['nickname'].'('.t('会员').'ID:'.$v['mid'].')';
			$tdata[] = $v['commission'] ? $v['commission'] : 0;
			$tdata[] = $v['score'] ? $v['score'] : 0;
			$tdata[] = $v['status']==0 ? '未发放' : '已发放';
			$tdata[] = date('Y-m-d H:i:s',$v['createtime']);
			$tdata[] = date('Y-m-d H:i:s',$v['endtime']);
			$tdata[] = $v['remark'];
			$data[] = $tdata;
		}
		$this->export_excel($title,$data);
	}
	//佣金记录删除
	public function recorddel(){
		$ids = input('post.ids/a');
		Db::name('member_commission_record')->where('aid',aid)->where('id','in',$ids)->delete();
		\app\common\System::plog('删除佣金记录'.implode(',',$ids));
		return json(['status'=>1,'msg'=>'删除成功']);
	}

	//佣金明细
    public function commissionlog(){
		if(request()->isAjax()){
			$page = input('param.page');
			$limit = input('param.limit');
			if(input('param.field') && input('param.order')){
				$order = 'member_commissionlog.'.input('param.field').' '.input('param.order');
			}else{
				$order = 'member_commissionlog.id desc';
			}
			$where = [];
			$where[] = ['member_commissionlog.aid','=',aid];
			
			if(input('param.nickname')) $where[] = ['member.nickname','like','%'.trim(input('param.nickname')).'%'];
			if(input('param.mid')) $where[] = ['member_commissionlog.mid','=',trim(input('param.mid'))];
			if(input('?param.status') && input('param.status')!=='') $where[] = ['member_commissionlog.status','=',input('param.status')];
			$count = 0 + Db::name('member_commissionlog')->alias('member_commissionlog')->field('member.nickname,member.headimg,member_commissionlog.*')->join('member member','member.id=member_commissionlog.mid')->where($where)->count();
			$data = Db::name('member_commissionlog')->alias('member_commissionlog')->field('member.nickname,member.headimg,member_commissionlog.*')->join('member member','member.id=member_commissionlog.mid')->where($where)->page($page,$limit)->order($order)->select()->toArray();
			
			foreach($data as $k=>$v){
				if($v['frommid']){
					$frommember = Db::name('member')->where('id',$v['frommid'])->find();
					if($frommember){
						$data[$k]['fromheadimg'] = $frommember['headimg'];
						$data[$k]['fromnickname'] = $frommember['nickname'];
					}
				}
			}

			return json(['code'=>0,'msg'=>'查询成功','count'=>$count,'data'=>$data]);
		}
		return View::fetch();
    }
	//佣金明细导出
	public function commissionlogexcel(){
		if(input('param.field') && input('param.order')){
			$order = 'member_commissionlog.'.input('param.field').' '.input('param.order');
		}else{
			$order = 'member_commissionlog.id desc';
		}
		$where = [];
		$where[] = ['member_commissionlog.aid','=',aid];
		
		if(input('param.nickname')) $where[] = ['member.nickname','like','%'.trim(input('param.nickname')).'%'];
		if(input('param.mid')) $where[] = ['member_commissionlog.mid','=',trim(input('param.mid'))];
		if(input('?param.status') && input('param.status')!=='') $where[] = ['member_commissionlog.status','=',input('param.status')];
		$list = Db::name('member_commissionlog')->alias('member_commissionlog')->field('member.nickname,member.headimg,member_commissionlog.*')->join('member member','member.id=member_commissionlog.mid')->where($where)->order($order)->select()->toArray();
		$title = array();
		$title[] = t('会员').'信息';
		$title[] = '变更金额';
		$title[] = '变更后金额';
		$title[] = '变更时间';
		$title[] = '备注';
		$data = array();
		foreach($list as $v){
			$tdata = array();
			$tdata[] = $v['nickname'].'('.t('会员').'ID:'.$v['mid'].')';
			$tdata[] = $v['commission'];
			$tdata[] = $v['after'];
			$tdata[] = date('Y-m-d H:i:s',$v['createtime']);
			$tdata[] = $v['remark'];
			$data[] = $tdata;
		}
		$this->export_excel($title,$data);
	}
	//佣金明细删除
	public function commissionlogdel(){
		$ids = input('post.ids/a');
		Db::name('member_commissionlog')->where('aid',aid)->where('id','in',$ids)->delete();
		\app\common\System::plog('删除佣金明细'.implode(',',$ids));
		return json(['status'=>1,'msg'=>'删除成功']);
	}
	//提现记录
	public function withdrawlog(){
		if(request()->isAjax()){
			$page = input('param.page');
			$limit = input('param.limit');
			if(input('param.field') && input('param.order')){
				$order = 'member_commission_withdrawlog.'.input('param.field').' '.input('param.order');
			}else{
				$order = 'member_commission_withdrawlog.id desc';
			}
			$where = array();
			$where[] = ['member_commission_withdrawlog.aid','=',aid];
			
			if(input('param.nickname')) $where[] = ['member.nickname','like','%'.trim(input('param.nickname')).'%'];
			if(input('param.mid')) $where[] = ['member_commission_withdrawlog.mid','=',trim(input('param.mid'))];
			if(input('?param.status') && input('param.status')!=='') $where[] = ['member_commission_withdrawlog.status','=',input('param.status')];
			$count = 0 + Db::name('member_commission_withdrawlog')->alias('member_commission_withdrawlog')->field('member.nickname,member.headimg,member_commission_withdrawlog.*')->join('member member','member.id=member_commission_withdrawlog.mid')->where($where)->count();
			$data = Db::name('member_commission_withdrawlog')->alias('member_commission_withdrawlog')->field('member.nickname,member.headimg,member_commission_withdrawlog.*')->join('member member','member.id=member_commission_withdrawlog.mid')->where($where)->page($page,$limit)->order($order)->select()->toArray();

			$comwithdrawbl = Db::name('admin_set')->where('aid',aid)->value('comwithdrawbl');
			foreach($data as $k=>$v){
				if($comwithdrawbl > 0 && $comwithdrawbl < 100){
					$data[$k]['paymoney'] = round($v['money'] * $comwithdrawbl * 0.01,2);
					$data[$k]['tomoney'] = round($v['money'] - $data[$k]['paymoney'],2);
				}else{
					$data[$k]['tomoney'] = 0;
				}
			}
			return json(['code'=>0,'msg'=>'查询成功','count'=>$count,'data'=>$data]);
		}
		return View::fetch();
    }
	//提现记录导出
	public function withdrawlogexcel(){
		if(input('param.field') && input('param.order')){
			$order = 'member_commission_withdrawlog.'.input('param.field').' '.input('param.order');
		}else{
			$order = 'member_commission_withdrawlog.id desc';
		}
		$where = [];
		$where[] = ['member_commission_withdrawlog.aid','=',aid];
		
		if(input('param.nickname')) $where[] = ['member.nickname','like','%'.trim(input('param.nickname')).'%'];
		if(input('param.mid')) $where[] = ['member_commission_withdrawlog.mid','=',trim(input('param.mid'))];
		if(input('?param.status') && input('param.status')!=='') $where[] = ['member_commission_withdrawlog.status','=',input('param.status')];
		$list = Db::name('member_commission_withdrawlog')->alias('member_commission_withdrawlog')->field('member.nickname,member.headimg,member_commission_withdrawlog.*')->join('member member','member.id=member_commission_withdrawlog.mid')->where($where)->order($order)->select()->toArray();
		$title = array();
		$title[] = t('会员').'信息';
		$title[] = '提现金额';
		$title[] = '打款金额';
		$title[] = '提现方式';
		$title[] = '收款账号';
		$title[] = '提现时间';
		$title[] = '状态';
		$data = array();
		foreach($list as $v){
			$tdata = array();
			$tdata[] = $v['nickname'].'('.t('会员').'ID:'.$v['mid'].')';
			$tdata[] = $v['txmoney'];
			$tdata[] = $v['money'];
			$tdata[] = $v['paytype'];
			if($v['paytype'] == '支付宝'){
				$tdata[] = $v['aliaccountname'].' '.$v['aliaccount'];
			}elseif($v['paytype'] == '银行卡'){
				$tdata[] = $v['bankname'] . ' - ' .$v['bankcarduser']. ' - '.$v['bankcardnum'];
			}else{
				$tdata[] = '';
			}
			$tdata[] = date('Y-m-d H:i:s',$v['createtime']);
			$st = '';
			if($v['status']==0){
				$st = '审核中';
			}elseif($v['status']==1){
				$st = '已审核';
			}elseif($v['status']==2){
				$st = '已驳回';
			}elseif($v['status']==3){
				$st = '已打款';
			}
			$tdata[] = $st;
			$data[] = $tdata;
		}
		$this->export_excel($title,$data);
	}
	//提现记录改状态
	public function withdrawlogsetst(){
		$id = input('post.id/d');
		$st = input('post.st/d');
		$reason = input('post.reason');
		$info = Db::name('member_commission_withdrawlog')->where('aid',aid)->where('id',$id)->find();
		
		$comwithdrawbl = Db::name('admin_set')->where('aid',aid)->value('comwithdrawbl');
		if($comwithdrawbl > 0 && $comwithdrawbl < 100){
			$paymoney = round($info['money'] * $comwithdrawbl * 0.01,2);
			$tomoney = round($info['money'] - $paymoney,2);
		}else{
			$paymoney = $info['money'];
			$tomoney = 0;
		}

		if($st==10){//微信打款
			if($info['status']!=1) return json(['status'=>0,'msg'=>'已审核状态才能打款']);
			$rs = \app\common\Wxpay::transfers(aid,$info['mid'],$paymoney,$info['ordernum'],$info['platform'],t('佣金').'提现');
			if($rs['status']==0){
				return json(['status'=>0,'msg'=>$rs['msg']]);
			}else{
				if($tomoney > 0){
					\app\common\Member::addmoney(aid,$info['mid'],$tomoney,t('佣金').'提现');
				}
				Db::name('member_commission_withdrawlog')->where('aid',aid)->where('id',$id)->update(['status'=>3,'paytime'=>time(),'paynum'=>$rs['resp']['payment_no']]);
				//提现成功通知
				$tmplcontent = [];
				$tmplcontent['first'] = '您的提现申请已打款，请留意查收';
				$tmplcontent['remark'] = '请点击查看详情~';
				$tmplcontent['money'] = (string) round($info['money'],2);
				$tmplcontent['timet'] = date('Y-m-d H:i',$info['createtime']);
				\app\common\Wechat::sendtmpl(aid,$info['mid'],'tmpl_tixiansuccess',$tmplcontent,m_url('pages/my/usercenter'));
				//订阅消息
				$tmplcontent = [];
				$tmplcontent['amount1'] = $info['money'];
				$tmplcontent['thing3'] = '微信打款';
				$tmplcontent['time5'] = date('Y-m-d H:i');
				
				$tmplcontentnew = [];
				$tmplcontentnew['amount3'] = $info['money'];
				$tmplcontentnew['phrase9'] = '微信打款';
				$tmplcontentnew['date8'] = date('Y-m-d H:i');
				\app\common\Wechat::sendwxtmpl(aid,$info['mid'],'tmpl_tixiansuccess',$tmplcontentnew,'pages/my/usercenter',$tmplcontent);
				//短信通知
				$member = Db::name('member')->where('id',$info['mid'])->find();
				if($member['tel']){
					$tel = $member['tel'];
					\app\common\Sms::send(aid,$tel,'tmpl_tixiansuccess',['money'=>$info['money']]);
				}
				return json(['status'=>1,'msg'=>$rs['msg']]);
				\app\common\System::plog('佣金提现微信打款'.$id);
			}
		}else{
			Db::name('member_commission_withdrawlog')->where('aid',aid)->where('id',$id)->update(['status'=>$st]);
			if($st == 2){//驳回返还佣金
				\app\common\Member::addcommission(aid,$info['mid'],0,$info['txmoney'],t('佣金').'提现返还',0);
				//提现失败通知
				$tmplcontent = [];
				$tmplcontent['first'] = '您的提现申请被商家驳回，可与商家协商沟通。';
				$tmplcontent['remark'] = $reason.'，请点击查看详情~';
				$tmplcontent['money'] = (string) round($info['txmoney'],2);
				$tmplcontent['time'] = date('Y-m-d H:i',$info['createtime']);
				\app\common\Wechat::sendtmpl(aid,$info['mid'],'tmpl_tixianerror',$tmplcontent,m_url('pages/my/usercenter'));
				//订阅消息
				$tmplcontent = [];
				$tmplcontent['amount1'] = $info['txmoney'];
				$tmplcontent['time3'] = date('Y-m-d H:i',$info['createtime']);
				$tmplcontent['thing4'] = $reason;
				
				$tmplcontentnew = [];
				$tmplcontentnew['thing1'] = '提现失败';
				$tmplcontentnew['amount2'] = $info['txmoney'];
				$tmplcontentnew['date4'] = date('Y-m-d H:i',$info['createtime']);
				$tmplcontentnew['thing12'] = $reason;
				\app\common\Wechat::sendwxtmpl(aid,$info['mid'],'tmpl_tixianerror',$tmplcontentnew,'pages/my/usercenter',$tmplcontent);
				//短信通知
				$member = Db::name('member')->where('id',$info['mid'])->find();
				if($member['tel']){
					$tel = $member['tel'];
					\app\common\Sms::send(aid,$tel,'tmpl_tixianerror',['reason'=>$reason]);
				}
				\app\common\System::plog('佣金提现驳回'.$id);
			}
			if($st==3){
				if($tomoney > 0){
					\app\common\Member::addmoney(aid,$info['mid'],$tomoney,t('佣金').'提现');
				}
				//提现成功通知
				$tmplcontent = [];
				$tmplcontent['first'] = '您的提现申请已打款，请留意查收';
				$tmplcontent['remark'] = '请点击查看详情~';
				$tmplcontent['money'] = (string) round($info['money'],2);
				$tmplcontent['timet'] = date('Y-m-d H:i',$info['createtime']);
				\app\common\Wechat::sendtmpl(aid,$info['mid'],'tmpl_tixiansuccess',$tmplcontent,m_url('pages/my/usercenter'));
				//订阅消息
				$tmplcontent = [];
				$tmplcontent['amount1'] = $info['money'];
				$tmplcontent['thing3'] = $info['paytype'];
				$tmplcontent['time5'] = date('Y-m-d H:i');
				
				$tmplcontentnew = [];
				$tmplcontentnew['amount3'] = $info['money'];
				$tmplcontentnew['phrase9'] = $info['paytype'];
				$tmplcontentnew['date8'] = date('Y-m-d H:i');
				\app\common\Wechat::sendwxtmpl(aid,$info['mid'],'tmpl_tixiansuccess',$tmplcontentnew,'pages/my/usercenter',$tmplcontent);
				//短信通知
				$member = Db::name('member')->where('id',$info['mid'])->find();
				if($member['tel']){
					$tel = $member['tel'];
					\app\common\Sms::send(aid,$tel,'tmpl_tixiansuccess',['money'=>$info['money']]);
				}
				\app\common\System::plog('佣金提现改为已打款'.$id);
			}
		}
		return json(['status'=>1,'msg'=>'操作成功']);
	}
	//提现记录删除
	public function withdrawlogdel(){
		$ids = input('post.ids/a');
		Db::name('member_commission_withdrawlog')->where('aid',aid)->where('id','in',$ids)->delete();
		\app\common\System::plog('佣金提现记录删除'.implode(',',$ids));
		return json(['status'=>1,'msg'=>'删除成功']);
	}

	
	//佣金明细
    public function fenhonglog(){
		if(request()->isAjax()){
			$page = input('param.page');
			$limit = input('param.limit');
			if(input('param.field') && input('param.order')){
				$order = 'member_fenhonglog.'.input('param.field').' '.input('param.order');
			}else{
				$order = 'member_fenhonglog.id desc';
			}
			$where = [];
			$where[] = ['member_fenhonglog.aid','=',aid];
			
			if(input('param.nickname')) $where[] = ['member.nickname','like','%'.trim(input('param.nickname')).'%'];
			if(input('param.mid')) $where[] = ['member_fenhonglog.mid','=',trim(input('param.mid'))];
			if(input('?param.status') && input('param.status')!=='') $where[] = ['member_fenhonglog.status','=',input('param.status')];
			$count = 0 + Db::name('member_fenhonglog')->alias('member_fenhonglog')->field('member.nickname,member.headimg,member_fenhonglog.*')->join('member member','member.id=member_fenhonglog.mid')->where($where)->count();
			$data = Db::name('member_fenhonglog')->alias('member_fenhonglog')->field('member.nickname,member.headimg,member_fenhonglog.*')->join('member member','member.id=member_fenhonglog.mid')->where($where)->page($page,$limit)->order($order)->select()->toArray();
			return json(['code'=>0,'msg'=>'查询成功','count'=>$count,'data'=>$data]);
		}
		return View::fetch();
    }
	//分红记录导出
	public function fenhonglogexcel(){
		if(input('param.field') && input('param.order')){
			$order = 'member_fenhonglog.'.input('param.field').' '.input('param.order');
		}else{
			$order = 'member_fenhonglog.id desc';
		}
		$where = [];
		$where[] = ['member_fenhonglog.aid','=',aid];
		
		if(input('param.nickname')) $where[] = ['member.nickname','like','%'.trim(input('param.nickname')).'%'];
		if(input('param.mid')) $where[] = ['member_fenhonglog.mid','=',trim(input('param.mid'))];
		if(input('?param.status') && input('param.status')!=='') $where[] = ['member_fenhonglog.status','=',input('param.status')];
		$list = Db::name('member_fenhonglog')->alias('member_fenhonglog')->field('member.nickname,member.headimg,member_fenhonglog.*')->join('member member','member.id=member_fenhonglog.mid')->where($where)->order($order)->select()->toArray();
		$title = array();
		$title[] = t('会员').'信息';
		$title[] = '分红金额';
		$title[] = '结算时间';
		$title[] = '备注';
		$data = array();
		foreach($list as $v){
			$tdata = array();
			$tdata[] = $v['nickname'].'('.t('会员').'ID:'.$v['mid'].')';
			$tdata[] = $v['commission'];
			$tdata[] = date('Y-m-d H:i:s',$v['createtime']);
			$tdata[] = $v['remark'];
			$data[] = $tdata;
		}
		$this->export_excel($title,$data);
	}
	//分红记录删除
	public function fenhonglogdel(){
		$ids = input('post.ids/a');
		Db::name('member_fenhonglog')->where('aid',aid)->where('id','in',$ids)->delete();
		\app\common\System::plog('删除分红记录'.implode(',',$ids));
		return json(['status'=>1,'msg'=>'删除成功']);
	}

	//团队分红--ttdz
	public function teamfenhong(){
		if(request()->isAjax()){
			$aid = aid;
			$sysset = Db::name('admin_set')->where('aid',aid)->find();
			$fhjiesuantype = $sysset['fhjiesuantype'];
			$fhjiesuantime = $sysset['fhjiesuantime'];
			$fhjiesuanbusiness = $sysset['fhjiesuanbusiness'];
			
			$type = input('param.type');
			if(!$type) $type = 1;
			if($type == 1){ //上月
				$starttime = strtotime(date('Y-m-01').' -1 month');
				$endtime = strtotime(date('Y-m-01'));
			}
			if($type == 2){ //本月
				$starttime = strtotime(date('Y-m-01'));
				$endtime = time();
			}
			if($type == 3){ //昨日
				$starttime = strtotime(date('Y-m-d'))-86400;
				$endtime = $starttime + 86400;
			}
			if($type == 4){ //今日
				$starttime = strtotime(date('Y-m-d'));
				$endtime = time();
			}
			if($type == 10){ //全部
				$starttime = 1;
				$endtime = time();
			}

			//多商户的商品是否参与分红
			if($fhjiesuanbusiness == 1){
				$bwhere = '1=1';
			}else{
				$bwhere = [['bid','=','0']];
			}
			if(getcustom('plug_ttdz')){
				$oglist = Db::name('shop_order_goods')->alias('og')->field('og.*,o.area2,m.nickname,m.headimg')->where('og.aid',aid)->where('og.isteamfenhong',0)->where('og.status',3)->join('shop_order o','o.id=og.orderid')->join('member m','m.id=og.mid')->where($bwhere)->where('og.endtime','>=',$starttime)->where('og.endtime','<',$endtime)->order('og.id desc')->select()->toArray();
			}else{
				$oglist = Db::name('shop_order_goods')->alias('og')->field('og.*,o.area2,m.nickname,m.headimg')->where('og.aid',aid)->where('og.isfenhong',0)->where('og.isteamfenhong',0)->where('og.status',3)->join('shop_order o','o.id=og.orderid')->join('member m','m.id=og.mid')->where($bwhere)->where('og.endtime','>=',$starttime)->where('og.endtime','<',$endtime)->order('og.id desc')->select()->toArray();
			}

			$newoglist = [];
			$commissionyj = 0;
			if($oglist){
                //参与团队分红的等级
                $teamfhlevellist = Db::name('member_level')->where('aid',aid)->where('teamfenhonglv','>','0')->where(function ($query) {
                    $query->where('teamfenhongbl','>',0)->whereOr('teamfenhong_money','>',0);
                })->column('id,cid,name,teamfenhonglv,teamfenhongbl,teamfenhongonly,teamfenhong_money,teamfenhong_self','id');
//参与等级团队分红的等级
                $level_teamfhlevellist = Db::name('member_level')->where('aid',aid)->where('level_teamfenhong_ids','<>','')->where('level_teamfenhonglv','>','0')->where(function ($query) {
                    $query->where('level_teamfenhongbl','>',0)->whereOr('level_teamfenhong_money','>',0);
                })->column('id,cid,name,level_teamfenhong_ids,level_teamfenhonglv,level_teamfenhongbl,level_teamfenhongonly,level_teamfenhong_money','id');

                $isjicha = ($sysset['teamfenhong_differential'] == 1 ? true : false);
				$allfenhongprice = 0;
				$ogids = [];
				$midfhArr = [];
				$midteamfhArr = [];
				$midareafhArr = [];
                $teamfenhong_orderids = [];
                $teamfenhong_orderids_cat = [];
                $level_teamfenhong_orderids = [];
                $level_teamfenhong_orderids_cat = [];
				foreach($oglist as $og){
					if($fhjiesuantype == 0){
						$fenhongprice = $og['real_totalprice'];
					}else{
						$fenhongprice = $og['real_totalprice'] - $og['cost_price'];
					}
					if($fenhongprice <= 0) continue;
					$ogids[] = $og['id'];
					$allfenhongprice = $allfenhongprice + $fenhongprice;

					$commission = 0;
					
					//团队分红
					if($teamfhlevellist){
						$pids = Db::name('member')->where('id',$og['mid'])->value('path');
                        if($pids) $pids .= ','.$og['mid'];
                        else $pids = (string)$og['mid'];
						if($pids){
							$parentList = Db::name('member')->where('id','in',$pids)->order(Db::raw('field(id,'.$pids.')'))->select()->toArray();
							$parentList = array_reverse($parentList);
							$hasfhlevelids = [];
							$last_teamfenhongbl = 0;
							foreach($parentList as $k=>$parent){
								$leveldata = $teamfhlevellist[$parent['levelid']];
								if(!$leveldata || $k>=$leveldata['teamfenhonglv']) continue;
                                if($parent['id'] == $og['mid'] && $leveldata['teamfenhong_self'] != 1) continue;
                                //每单奖励
                                if($leveldata['teamfenhong_money'] > 0 && !in_array($og['orderid'],$teamfenhong_orderids)) {
                                    $fenhongmoney = $leveldata['teamfenhong_money'];
                                    $commission += $fenhongmoney;
                                    $teamfenhong_orderids[] = $og['orderid'];
                                }
                                //分红比例
								if($isjicha){
									$this_teamfenhongbl = $leveldata['teamfenhongbl'] - $last_teamfenhongbl;
								}else{
									$this_teamfenhongbl = $leveldata['teamfenhongbl'];
								}
								if($this_teamfenhongbl <=0) continue;
								$last_teamfenhongbl = $last_teamfenhongbl + $this_teamfenhongbl;

								if($leveldata['teamfenhongonly'] == 1 && in_array($parent['levelid'],$hasfhlevelids)) continue; //该等级设置了只给最近的上级分红
								$hasfhlevelids[] = $parent['levelid'];

								$fenhongmoney = $this_teamfenhongbl * $fenhongprice * 0.01;
								//if($parent['id'] == mid){
									$commission += $fenhongmoney;
								//}
							}
							//其他分组等级
							if(getcustom('plug_sanyang')) {
								$catList = Db::name('member_level_category')->where('aid', aid)->where('isdefault', 0)->select()->toArray();
								foreach ($catList as $cat) {
									$parentList = Db::name('member_level_record')->field('mid id,levelid')->where('aid', aid)->where('cid', $cat['id'])->whereIn('mid', $pids)->select()->toArray();
									$parentList = array_reverse($parentList);
									$hasfhlevelids = [];
									$last_teamfenhongbl = 0;
									foreach($parentList as $k=>$parent){
										$leveldata = $teamfhlevellist[$parent['levelid']];
										if(!$leveldata || $k>=$leveldata['teamfenhonglv']) continue;
                                        if($parent['id'] == $og['mid'] && $leveldata['teamfenhong_self'] != 1) continue;
                                        //每单奖励
                                        if($leveldata['teamfenhong_money'] > 0 && !in_array($og['orderid'],$teamfenhong_orderids_cat)) {
                                            $fenhongmoney = $leveldata['teamfenhong_money'];
                                            $commission += $fenhongmoney;
                                            $teamfenhong_orderids_cat[] = $og['orderid'];
                                        }
                                        //分红比例
										if($isjicha){
											$this_teamfenhongbl = $leveldata['teamfenhongbl'] - $last_teamfenhongbl;
										}else{
											$this_teamfenhongbl = $leveldata['teamfenhongbl'];
										}
										if($this_teamfenhongbl <=0) continue;
										$last_teamfenhongbl = $last_teamfenhongbl + $this_teamfenhongbl;

										if($leveldata['teamfenhongonly'] == 1 && in_array($parent['levelid'],$hasfhlevelids)) continue; //该等级设置了只给最近的上级分红
										$hasfhlevelids[] = $parent['levelid'];

										$fenhongmoney = $this_teamfenhongbl * $fenhongprice * 0.01;
										//if($parent['id'] == mid){
											$commission += $fenhongmoney;
										//}
									}
								}
							}
						}
					}

                    //等级团队分红
                    if(getcustom('level_teamfenhong')) {
                        if($level_teamfhlevellist){
                            $pids = Db::name('member')->where('id',$og['mid'])->value('path');
                            if($pids){
                                //查询符合等级条件的
                                $level_teamfenhong_ids = [];
                                foreach($level_teamfhlevellist as $level) {
                                    $temp = explode(',',(string)$level['level_teamfenhong_ids']);
                                    $level_teamfenhong_ids = array_merge($level_teamfenhong_ids, $temp);
                                }
                                $level_teamfenhong_ids = array_unique($level_teamfenhong_ids);
                                $parentList = Db::name('member')->where('id','in',$pids)->whereIn('levelid',$level_teamfenhong_ids)->order(Db::raw('field(id,'.$pids.')'))->select()->toArray();
                                $parentList = array_reverse($parentList);
                                $hasfhlevelids = [];
                                $last_teamfenhongbl = 0;
                                foreach($parentList as $k=>$parent){
                                    $leveldata = $level_teamfhlevellist[$parent['levelid']];
                                    if(!$leveldata || $k>=$leveldata['level_teamfenhonglv']) continue;
                                    //每单奖励
                                    if($leveldata['level_teamfenhong_money'] > 0 && !in_array($og['orderid'], $level_teamfenhong_orderids[$parent['id']])) {
                                        $fenhongmoney = $leveldata['level_teamfenhong_money'];
                                        $level_teamfenhong_orderids[$parent['id']][] = $og['orderid'];
//                                        if($parent['id'] == mid){
                                            $commission += $fenhongmoney;
//                                        }
                                    }
                                    //分红比例
                                    if($leveldata['level_teamfenhongbl'] > 0) {
                                        if($isjicha){
                                            $this_teamfenhongbl = $leveldata['level_teamfenhongbl'] - $last_teamfenhongbl;
                                        }else{
                                            $this_teamfenhongbl = $leveldata['level_teamfenhongbl'];
                                        }
                                        if($this_teamfenhongbl <=0) continue;
                                        $last_teamfenhongbl = $last_teamfenhongbl + $this_teamfenhongbl;

                                        if($leveldata['level_teamfenhongonly'] == 1 && in_array($parent['levelid'],$hasfhlevelids)) continue; //该等级设置了只给最近的上级分红
                                        $hasfhlevelids[] = $parent['levelid'];

                                        $fenhongmoney = $this_teamfenhongbl * $fenhongprice * 0.01;
//                                        if($parent['id'] == mid){
                                            $commission += $fenhongmoney;
//                                        }
                                    }
                                }
                                //其他分组等级
                                if(getcustom('plug_sanyang')) {
                                    $catList = Db::name('member_level_category')->where('aid', aid)->where('isdefault', 0)->select()->toArray();
                                    foreach ($catList as $cat) {
                                        $parentList = Db::name('member_level_record')->field('mid id,levelid')->where('aid', aid)->whereIn('levelid',$level_teamfenhong_ids)->where('cid', $cat['id'])->whereIn('mid', $pids)->select()->toArray();
                                        $parentList = array_reverse($parentList);
                                        $hasfhlevelids = [];
                                        $last_teamfenhongbl = 0;
                                        foreach($parentList as $k=>$parent){

                                            $leveldata = $level_teamfhlevellist[$parent['levelid']];
                                            if(!$leveldata || $k>=$leveldata['level_teamfenhonglv']) continue;
                                            if($parent['id'] == $og['mid'] && $leveldata['teamfenhong_self'] != 1) continue;
                                            //每单奖励
                                            if($leveldata['level_teamfenhong_money'] > 0 && !in_array($og['orderid'], $level_teamfenhong_orderids_cat[$parent['id']])) {
                                                $fenhongmoney = $leveldata['level_teamfenhong_money'];
                                                $level_teamfenhong_orderids_cat[$parent['id']][] = $og['orderid'];
//                                                if($parent['id'] == mid){
                                                    $commission += $fenhongmoney;
//                                                }
                                            }
                                            //分红比例
                                            if($leveldata['level_teamfenhongbl'] > 0) {
                                                if($isjicha){
                                                    $this_teamfenhongbl = $leveldata['level_teamfenhongbl'] - $last_teamfenhongbl;
                                                }else{
                                                    $this_teamfenhongbl = $leveldata['level_teamfenhongbl'];
                                                }
                                                if($this_teamfenhongbl <=0) continue;
                                                $last_teamfenhongbl = $last_teamfenhongbl + $this_teamfenhongbl;

                                                if($leveldata['level_teamfenhongonly'] == 1 && in_array($parent['levelid'],$hasfhlevelids)) continue; //该等级设置了只给最近的上级分红
                                                $hasfhlevelids[] = $parent['levelid'];

                                                $fenhongmoney = $this_teamfenhongbl * $fenhongprice * 0.01;
//                                                if($parent['id'] == mid){
                                                    $commission += $fenhongmoney;
//                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }


					if($commission > 0){
						$commissionyj += $commission;
						$og['commission'] = round($commission,2);
						$newoglist[] = $og;
					}
					$commissionyj = round($commissionyj,2);
				}
			}
			return json(['code'=>0,'msg'=>'查询成功','type'=>$type,'count'=>count($newoglist),'data'=>$newoglist,'commissionyj'=>$commissionyj]);
		}
		return View::fetch();
	}
	//团队分红发放--ttdz
	public function teamfenhongfafang(){
		$aid = aid;
		$sysset = Db::name('admin_set')->where('aid',aid)->find();
		$fhjiesuantype = $sysset['fhjiesuantype'];
		$fhjiesuantime = $sysset['fhjiesuantime'];
		$fhjiesuanbusiness = $sysset['fhjiesuanbusiness'];
		
		$type = input('param.type');
		if(!$type) $type = 1;
		if($type == 1){ //上月
			$starttime = strtotime(date('Y-m-01').' -1 month');
			$endtime = strtotime(date('Y-m-01'));
		}
		if($type == 2){ //本月
			$starttime = strtotime(date('Y-m-01'));
			$endtime = time();
		}
		if($type == 3){ //昨日
			$starttime = strtotime(date('Y-m-d'))-86400;
			$endtime = $starttime + 86400;
		}
		if($type == 4){ //今日
			$starttime = strtotime(date('Y-m-d'));
			$endtime = time();
		}
		if($type == 10){ //全部
			$starttime = 1;
			$endtime = time();
		}

		//多商户的商品是否参与分红
		if($fhjiesuanbusiness == 1){
			$bwhere = '1=1';
		}else{
			$bwhere = [['og.bid','=','0']];
		}

		if(getcustom('plug_ttdz')){
			$oglist = Db::name('shop_order_goods')->alias('og')->field('og.*,o.area2,m.nickname,m.headimg')->where('og.aid',aid)->where('og.isteamfenhong',0)->where('og.status',3)->join('shop_order o','o.id=og.orderid')->join('member m','m.id=og.mid')->where($bwhere)->where('og.endtime','>=',$starttime)->where('og.endtime','<',$endtime)->order('og.id desc')->select()->toArray();
		}else{
			$oglist = Db::name('shop_order_goods')->alias('og')->field('og.*,o.area2,m.nickname,m.headimg')->where('og.aid',aid)->where('og.isfenhong',0)->where('og.isteamfenhong',0)->where('og.status',3)->join('shop_order o','o.id=og.orderid')->join('member m','m.id=og.mid')->where($bwhere)->where('og.endtime','>=',$starttime)->where('og.endtime','<',$endtime)->order('og.id desc')->select()->toArray();
		}

		if(!$oglist) return json(['status'=>0,'msg'=>'没有未发放的团队分红订单']);
		
		//参与团队分红的等级
		$teamfhlevellist = Db::name('member_level')->where('aid',$aid)->where('teamfenhonglv','>','0')->where(function ($query) {
            $query->where('teamfenhongbl','>',0)->whereOr('teamfenhong_money','>',0);
        })->column('id,cid,name,teamfenhonglv,teamfenhongbl,teamfenhongonly,teamfenhong_money,teamfenhong_self','id');

		$defaultCid = Db::name('member_level_category')->where('aid',$aid)->where('isdefault', 1)->value('id');
		
		$isjicha = ($sysset['teamfenhong_differential'] == 1 ? true : false);
		$allfenhongprice = 0;
		$ogids = [];
		$midfhArr = [];
		$midteamfhArr = [];
		$midareafhArr = [];
        $teamfenhong_orderids = [];
        $teamfenhong_orderids_cat = [];
		foreach($oglist as $og){
			if($fhjiesuantype == 0){
				$fenhongprice = $og['real_totalprice'];
			}else{
				$fenhongprice = $og['real_totalprice'] - $og['cost_price'];
			}
			if($fenhongprice <= 0) continue;
			$ogids[] = $og['id'];
			$allfenhongprice = $allfenhongprice + $fenhongprice;

			//团队分红
			if($teamfhlevellist){
				$pids = Db::name('member')->where('id',$og['mid'])->value('path');
                if($pids) $pids .= ','.$og['mid'];
                else $pids = (string)$og['mid'];
				if($pids){
					$parentList = Db::name('member')->where('id','in',$pids)->order(Db::raw('field(id,'.$pids.')'))->select()->toArray();
					$parentList = array_reverse($parentList);
					$hasfhlevelids = [];
					$last_teamfenhongbl = 0;
					foreach($parentList as $k=>$parent){
						$leveldata = $teamfhlevellist[$parent['levelid']];
						if(!$leveldata || $k>=$leveldata['teamfenhonglv']) continue;
                        if($parent['id'] == $og['mid'] && $leveldata['teamfenhong_self'] != 1) continue;
                        //每单奖励
                        if($leveldata['teamfenhong_money'] > 0 && !in_array($og['orderid'],$teamfenhong_orderids[$parent['id']])) {
                            $fenhongmoney = $leveldata['teamfenhong_money'];
                            if($midteamfhArr[$parent['id']]){
                                $midteamfhArr[$parent['id']]['commission'] =  $midteamfhArr[$parent['id']]['commission'] + $fenhongmoney;
                                $midteamfhArr[$parent['id']]['ogids'][] = $og['id'];
                            } else {
                                $midteamfhArr[$parent['id']] = ['commission'=>$fenhongmoney,'ogids'=>[$og['id']]];
                            }
                            $teamfenhong_orderids[$parent['id']][] = $og['orderid'];
                        }
                        //分红比例
						if($isjicha){
							$this_teamfenhongbl = $leveldata['teamfenhongbl'] - $last_teamfenhongbl;
						}else{
							$this_teamfenhongbl = $leveldata['teamfenhongbl'];
						}
						if($this_teamfenhongbl <=0) continue;
						$last_teamfenhongbl = $last_teamfenhongbl + $this_teamfenhongbl;
						
						if($leveldata['teamfenhongonly'] == 1 && in_array($parent['levelid'],$hasfhlevelids)) continue; //该等级设置了只给最近的上级分红
						$hasfhlevelids[] = $parent['levelid'];

						$fenhongmoney = $this_teamfenhongbl * $fenhongprice * 0.01;
						if($midteamfhArr[$parent['id']]){
							$midteamfhArr[$parent['id']]['commission'] = $midteamfhArr[$parent['id']]['commission'] + $fenhongmoney;
							$midteamfhArr[$parent['id']]['ogids'][] = $og['id'];
						}else{
							$midteamfhArr[$parent['id']] = ['commission'=>$fenhongmoney,'ogids'=>[$og['id']]];
						}
					}
					//其他分组等级
					if(getcustom('plug_sanyang')) {
						$catList = Db::name('member_level_category')->where('aid', $aid)->where('isdefault', 0)->select()->toArray();
						foreach ($catList as $cat) {
							$parentList = Db::name('member_level_record')->field('mid id,levelid')->where('aid', $aid)->where('cid', $cat['id'])->whereIn('mid', $pids)->select()->toArray();
							$parentList = array_reverse($parentList);
							$hasfhlevelids = [];
							$last_teamfenhongbl = 0;
							foreach($parentList as $k=>$parent){
								$leveldata = $teamfhlevellist[$parent['levelid']];
								if(!$leveldata || $k>=$leveldata['teamfenhonglv']) continue;
                                if($parent['id'] == $og['mid'] && $leveldata['teamfenhong_self'] != 1) continue;
                                //每单奖励
                                if($leveldata['teamfenhong_money'] > 0 && !in_array($og['orderid'],$teamfenhong_orderids_cat[$parent['id']])) {
                                    $fenhongmoney = $leveldata['teamfenhong_money'];
                                    if($midteamfhArr[$parent['id']]){
                                        $midteamfhArr[$parent['id']]['commission'] =  $midteamfhArr[$parent['id']]['commission'] + $fenhongmoney;
                                        $midteamfhArr[$parent['id']]['ogids'][] = $og['id'];
                                    } else {
                                        $midteamfhArr[$parent['id']] = ['commission'=>$fenhongmoney,'ogids'=>[$og['id']]];
                                    }
                                    $teamfenhong_orderids_cat[$parent['id']] = $og['orderid'];
                                }
                                //分红比例
								if($isjicha){
									$this_teamfenhongbl = $leveldata['teamfenhongbl'] - $last_teamfenhongbl;
								}else{
									$this_teamfenhongbl = $leveldata['teamfenhongbl'];
								}
								if($this_teamfenhongbl <=0) continue;
								$last_teamfenhongbl = $last_teamfenhongbl + $this_teamfenhongbl;

								if($leveldata['teamfenhongonly'] == 1 && in_array($parent['levelid'],$hasfhlevelids)) continue; //该等级设置了只给最近的上级分红
								$hasfhlevelids[] = $parent['levelid'];

								$fenhongmoney = $this_teamfenhongbl * $fenhongprice * 0.01;
								
								if($midteamfhArr[$parent['id']]){
									$midteamfhArr[$parent['id']]['commission'] += $fenhongmoney;
									$midteamfhArr[$parent['id']]['ogids'][] = $og['id'];
								}else{
									$midteamfhArr[$parent['id']] = ['commission'=>$fenhongmoney,'ogids'=>[$og['id']]];
								}
							}
						}
					}
				}
			}
			Db::name('shop_order_goods')->where('aid',$aid)->where('id',$og['id'])->update(['isteamfenhong'=>1]);
		}
		$totalcommission = 0;
		if($midteamfhArr){
			foreach($midteamfhArr as $mid=>$midfh){
				$commission = $midfh['commission'];
				$commission = round($commission,2);
				$fhdata = [];
				$fhdata['aid'] = $aid;
				$fhdata['mid'] = $mid;
				$fhdata['commission'] = $commission;
				$fhdata['remark'] = t('团队分红');
				$fhdata['type'] = 'teamfenhong';
				$fhdata['createtime'] = time();
				$fhdata['ogids'] = implode(',',$midfh['ogids']);
				Db::name('member_fenhonglog')->insert($fhdata);
				\app\common\Member::addcommission($aid,$mid,0,$commission,$fhdata['remark']);
				$totalcommission += $commission;
			}
		}
		return json(['status'=>1,'msg'=>'发放完成，共发放佣金：'.$totalcommission.'元','totalcommission'=>$totalcommission]);
	}
}
